package com.wing.api.add.device.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.wing.api.add.device.BaseDeviceService;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.common.exception.BusinessException;
import com.wing.enterprise.device.request.DeviceForm;
import com.wing.enterprise.feign.EnterpriseClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * 标准设备接口
 */
@Service
@Slf4j
public class StandardDeviceServiceImpl implements BaseDeviceService {

    @Transactional
    @Override
    public void logicProcess(DeviceForm deviceForm, EnterpricceIdVO enterpricceIdVo, EnterpriseClient enterpriseClient) throws IOException {
//        log.info("请求参数,{}", jsonObject.toJSONString());
        //此处需要做接口签名验证
        //sign = md5（参数1+参数2+参数3+key）
        String sourceSign = deviceForm.getSign(); // 签名值
        String deviceCode = deviceForm.getDeviceCode(); // 设备编码
        String name = deviceForm.getName(); // 设备名称

        if(StringUtils.isBlank(sourceSign)){
            throw new BusinessException("签名值为空！");
        }
        if(StringUtils.isBlank(deviceCode)){
            throw new BusinessException("设备编码为空！");
        }
        if(StringUtils.isBlank(name)){
            throw new BusinessException("设备名称为空！");
        }

        StringBuffer tempStr = new StringBuffer();
        tempStr.append(deviceCode);
        tempStr.append(name);
        tempStr.append(enterpricceIdVo.getKey());
        log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex(tempStr.toString());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }
        enterpriseClient.addDevice(deviceForm);

    }
    public static void main(String[] args) {
        String key = "$2a$10$fxpgo/SLFHCeNThnfF/q7uvoZJOxbJBNNI4.dshzlntgBIHKI9eb."; // 测试
        String desSign2= DigestUtil.md5Hex("T-02T设备2"+ key);
        System.out.println(desSign2);
    }
}
